#include "EventController.h"
#include "EventHolder.h"
#include "EventRegistrator.h"

namespace cevent {
	EventController EventController::eventController;
	const EventListener* findEventByEvent::compare_to;
	const EventListener* findWrapEvent::compare_to;
	long EventRegistrator::ID_NEXT = 0;

	EventController::EventController()
	{

	}

	EventController::~EventController()
	{
		
	}

	void EventController::GenerateEvent(void* sender, EventArgs* e, std::list<EventListenerWrap*>& baseEventList) {
		for (std::list<EventListenerWrap*>::iterator it = baseEventList.begin(); it != baseEventList.end();)
		{
			EventListenerWrap* eventListenerWrap = *it;
			if (eventListenerWrap->isDispose) {
				it = baseEventList.erase(it);
				DELETE(eventListenerWrap);
				continue;
			}
			if (eventListenerWrap->eventListener->handler->GetSender() == sender) {
				if (eventListenerWrap->eventListener->handler->Call(e)) {
					break;
				}
			}
			++it;
		}
	}

	void EventController::UnRegisterEventListener(EventListener* event) {
		EventRegistrator* eventRegistrator = (EventRegistrator*)(event->eventRegistrator);
		std::list<EventListenerWrap*>& eventQueue = eventRegistrator->eventsChain;
		if (isGenEvent) { // if isGenEvent == true, we dispose EventWrap and let GenerateEvent to handle it
			findWrapEvent::compare_to = event;
			std::list<EventListenerWrap*>::iterator it = std::find_if(eventQueue.begin(), eventQueue.end(), findWrapEvent()); // search in the list...oh...need to change it
			if (it != eventQueue.end())
				(*it)->dispose();
		}
		else { // if isGenEvent == false we can safe erase this event from eventQueue
			findWrapEvent::compare_to = event;
			std::list<EventListenerWrap*>::iterator it = std::find_if(eventQueue.begin(), eventQueue.end(), findWrapEvent()); // search in the list...oh...need to change it
			if (it != eventQueue.end()) {
				DELETE(*it);
				eventQueue.erase(it);
			}
		}
	}
}